package com.chens.common.exception;

import com.chens.payload.ApiResponse;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UnauthorizedException.class)
    public ApiResponse<Void> handleUnauthorizedException(UnauthorizedException ex, HttpServletRequest request) {
        return ApiResponse.error(ex.getMessage());
    }

    @ExceptionHandler(BadCredentialsException.class)
    public ApiResponse<Void> handleBadCredentialsException(BadCredentialsException ex, HttpServletRequest request) {
        return ApiResponse.error("Invalid username or password");
    }

    @ExceptionHandler(DisabledException.class)
    public ApiResponse<Void> handleDisabledException(DisabledException ex, HttpServletRequest request) {
        return ApiResponse.error("User account is disabled");
    }

    @ExceptionHandler(LockedException.class)
    public ApiResponse<Void> handleLockedException(LockedException ex, HttpServletRequest request) {
        return ApiResponse.error("User account is locked");
    }

    @ExceptionHandler({ExpiredJwtException.class, MalformedJwtException.class, SignatureException.class, UnsupportedJwtException.class})
    public ApiResponse<Void> handleJwtExceptions(Exception ex, HttpServletRequest request) {
        String message;
        if (ex instanceof ExpiredJwtException) {
            message = "JWT token has expired";
        } else if (ex instanceof MalformedJwtException) {
            message = "Invalid JWT token";
        } else if (ex instanceof SignatureException) {
            message = "Invalid JWT signature";
        } else if (ex instanceof UnsupportedJwtException) {
            message = "Unsupported JWT token";
        } else {
            message = "JWT authentication failed";
        }

        return ApiResponse.error(message);
    }

    @ExceptionHandler(RuntimeException.class)
    public ApiResponse<Void> handleRuntimeException(RuntimeException ex, HttpServletRequest request) {
        return ApiResponse.error(ex.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public ApiResponse<?> handleGlobalException(Exception ex) {
        return ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器内部错误");
    }
}